package com.manager.devicemanager.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manager.devicemanager.common.DataSourceNameEnum;
import com.manager.devicemanager.common.ICComponentPriority;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.entity.*;
import com.manager.devicemanager.service.*;
import com.manager.devicemanager.util.StringDealUtils;
import com.manager.devicemanager.vo.ComponentStatusRequestVO;
import com.manager.devicemanager.vo.ICBoardDeviceInfo;
import com.manager.devicemanager.vo.PageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wpf
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/board1")
public class Board1Controller {
    @Autowired
    private IBoard1Service boardService;
    @Autowired
    private IComponentStatusService iComponentStatusService;
    @Autowired
    private IComponentRunStatus1Service iComponentRunStatus1Service;
    @Autowired
    private IIcboardRealtimeService icboardRealtimeService;
    @Autowired
    private IDevicestatusService iDevicestatusService;

    /**
     * 带条件筛选的分页查询接口
     *
     * @param pageVO 分页查询条件对象，包含页码、每页数量和查询条件
     * @return 分页查询结果
     */
    @Operation(summary = "带条件筛选的分页查询")
    @PostMapping("/page")
    public Result<IPage<Board1>> page(@Parameter(description = "分页查询条件对象") @RequestBody PageVO<Board1> pageVO) {
        // 获取分页参数
        int pageNum = pageVO.getPageNum();
        int pageSize = pageVO.getPageSize();
        // 获取查询条件
        Board1 condition = pageVO.getCondition();

        // 构建查询条件包装器
        LambdaQueryWrapper<Board1> queryWrapper = new LambdaQueryWrapper<>(condition);

        // 执行分页查询
        IPage<Board1> pageResult = boardService.page(new Page<>(pageNum, pageSize), queryWrapper);

        return Result.success(pageResult);
    }

    @Operation(summary = "查询最新一条IC数据")
    @PostMapping("/selectLastICOne/{testid}")
    public Result<List<BoardDeviceInfo>> selectLastICOne(@PathVariable("testid") String testid,@RequestBody ComponentStatusRequestVO componentStatusRequestVO) {
        List<IcboardRealtime> icboardRealtimes = icboardRealtimeService.selectLimit12(DataSourceNameEnum.ICBOARDATA.getDataSourceName()+componentStatusRequestVO.getDatasourceindex(),testid);
        List<BoardDeviceInfo> boardDeviceInfos = new ArrayList<>();
        for (IcboardRealtime icboardRealtime : icboardRealtimes) {
            BoardDeviceInfo deviceInfo = new BoardDeviceInfo();
            deviceInfo.set板卡ID(icboardRealtime.getBoardid());
            deviceInfo.set整板电压(icboardRealtime.getVoltage().toString());
            deviceInfo.set整板电流(icboardRealtime.getCurrent().toString());
            deviceInfo.set状态(icboardRealtime.getStatus());
            deviceInfo.set数据时间戳(icboardRealtime.getTimestamp().toString());
            ComponentStatus lastData = iComponentStatusService.getLastData(DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName()+componentStatusRequestVO.getDatasourceindex());
            if (lastData == null) {
                lastData = new ComponentStatus();
            }
            String methodName2 = "getS" + icboardRealtime.getBoardid();
            try {
                java.lang.reflect.Method method = ComponentStatus.class.getMethod(methodName2);
                String jsonData = (String) method.invoke(lastData);
                // 判断结果是否为JSON格式或单值
                boolean isJson = jsonData != null &&
                        (jsonData.trim().startsWith("{") || jsonData.trim().startsWith("["));
//                String dataType = isJson ? "JSON" : "单值";
//                System.out.println("数据类型: " + dataType);
                // 处理JSON数据：补全1-48组件状态（缺失项默认为0-正常）
                Integer[] status=new Integer[48];
                for (int i = 0; i < 48; i++) {
                    status[i]=0;
                }
                if (isJson) {
                    JSONObject jsonObject = JSONObject.parseObject(jsonData);
                    Set<String> keys = jsonObject.keySet();
                    for (String key : keys) {
                        int componentId = Integer.parseInt(key);
                        // 缺失的组件ID默认状态为0（正常）
                        int statusCode = jsonObject.getIntValue(""+componentId, 0);
                        status[componentId-1]=statusCode;
                    }
                    countStatusIC(status,deviceInfo);
                }else {
                    Integer statusCode = Integer.parseInt(jsonData);
                    // 根据状态码设置对应计数为48
                    switch (statusCode) {
                        case 0:
                            deviceInfo.setStatus_cnt1(48);
                            break;
                        case 6:
                            deviceInfo.setStatus_cnt2(48);
                            break;
                        case 9:
                            deviceInfo.setStatus_cnt3(48);
                            break;
                        case 10:
                            deviceInfo.setStatus_cnt4(48);
                            break;
                        // 可根据需要添加其他状态码的处理逻辑
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            boardDeviceInfos.add(deviceInfo);
        }
        return Result.success(boardDeviceInfos);

//        try {
//            Board1 board1 = boardService.selectLastICOne(DataSourceNameEnum.ICBOARDATA.getDataSourceName()+componentStatusRequestVO.getDatasourceindex(), testid);
//            if (board1 == null) return Result.success(new ArrayList<>());
//            else {
//                ComponentStatus lastData = iComponentStatusService.getLastData(DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName()+componentStatusRequestVO.getDatasourceindex());
//                if (lastData == null) {
//                    lastData = new ComponentStatus();
//                }
//                List<BoardDeviceInfo> boardDeviceInfos = new ArrayList<>();
//
//
//                for (int i = 1; i <= 12; i++) {
//                    String methodName = "getB" + i;
//                    String methodName2 = "getS" + i;
//                    try {
//                        java.lang.reflect.Method method = Board1.class.getMethod(methodName);
//                        java.lang.reflect.Method method1 = ComponentStatus.class.getMethod(methodName2);
//                        String jsonData = (String) method.invoke(board1);
//                        BoardDeviceInfo deviceInfo = convertJsonToBoardDeviceInfo(jsonData);
//                        countStatus((String) method1.invoke(lastData), deviceInfo);
//                        boardDeviceInfos.add(deviceInfo);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//                return Result.success(boardDeviceInfos);
//            }
//        } catch (Exception e) {
//            return Result.error(e.getMessage());
//        }

    }
    /**
     * 统计不同状态的数量并设置到 BoardDeviceInfo 对象中
     *
     * @param data       待统计的字符串数据
     * @param deviceInfo 要设置状态数量的 BoardDeviceInfo 对象
     */
    private void countStatusIC(Integer[] data, BoardDeviceInfo deviceInfo) {
        int status_cnt1 = 0;
        int status_cnt2 = 0;
        int status_cnt3 = 0;
        int status_cnt4 = 0;
        if (data != null) {
            for (Integer part : data) {
                switch (part) {
                    case 0:
                        status_cnt1++;
                        break;
                    case 6:
                        status_cnt2++;
                        break;
                    case 9:
                        status_cnt3++;
                        break;
                    case 10:
                        status_cnt4++;
                        break;
                }
            }
        }

        deviceInfo.setStatus_cnt1(status_cnt1);
        deviceInfo.setStatus_cnt2(status_cnt2);
        deviceInfo.setStatus_cnt3(status_cnt3);
        deviceInfo.setStatus_cnt4(status_cnt4);
    }




    private void countStatusDP(String data, BoardDeviceInfo deviceInfo) {
        int status_cnt1 = 0;
        int status_cnt2 = 0;
        int status_cnt3 = 0;
        int status_cnt4 = 0;

        if (data != null) {
            data = StringDealUtils.dealDPComponentString(data);
            String[] parts = data.split(":");
            for (String part : parts) {
                switch (part) {
                    case "正常":
                        status_cnt1++;
                        break;
                    case "烧毁":
                        status_cnt2++;
                        break;
                    case "退化":
                        status_cnt3++;
                        break;
                    case "断电":
                        status_cnt4++;
                        break;
                }
            }
        }

        deviceInfo.setStatus_cnt1(status_cnt1);
        deviceInfo.setStatus_cnt2(status_cnt2);
        deviceInfo.setStatus_cnt3(status_cnt3);
        deviceInfo.setStatus_cnt4(status_cnt4);
    }

    @Operation(summary = "查询最新一条DP数据")
    @PostMapping("/selectLastDPOne/{testid}")
    public Result<List<BoardDeviceInfo>> selectLastDPOne(@PathVariable("testid") String testid,@RequestBody ComponentStatusRequestVO componentStatusRequestVO) {
        Board1 board1 = boardService.selectLastDPOne(DataSourceNameEnum.PDBOARDATA.getDataSourceName()+componentStatusRequestVO.getDatasourceindex(), testid);
        Devicestatus devicestatus = iDevicestatusService.getDataList(DataSourceNameEnum.PDBOARDCONFIG.getDataSourceName()+componentStatusRequestVO.getDatasourceindex());

        if (board1 == null) return Result.success(new ArrayList<>());
        else {
            List<BoardDeviceInfo> boardDeviceInfos = new ArrayList<>();
            ComponentRunStatus1 lastData = iComponentRunStatus1Service.getLastData(DataSourceNameEnum.PDBOARDCONFIG.getDataSourceName()+componentStatusRequestVO.getDatasourceindex());
            if (lastData == null) {
                lastData = new ComponentRunStatus1();
            }
            for (int i = 1; i <= 18; i++) {
                String methodName = "getB" + i;
                String methodName2 = "getS" + i;
                try {
                    java.lang.reflect.Method method = Board1.class.getMethod(methodName);
                    java.lang.reflect.Method method1 = ComponentRunStatus1.class.getMethod(methodName2);
                    java.lang.reflect.Method method2 = Devicestatus.class.getMethod(methodName);
                    String jsonData = (String) method.invoke(board1);
                    jsonData = jsonData.replaceAll("^\"|\"$", "");
                    String[] parts = jsonData.split(":");


                    BoardDeviceInfo deviceInfo = new BoardDeviceInfo();
                    deviceInfo.set板卡ID(i);
                    deviceInfo.set温度(parts[1]);
                    deviceInfo.set整板电压(parts[0]);
                    // 将 Date 转换为 LocalDateTime
                    Instant instant = board1.getTimestamp().toInstant();
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                    // 定义时间格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    // 格式化时间
                    String formattedTime = localDateTime.format(formatter);
                    deviceInfo.set数据时间戳(formattedTime);
                    if (devicestatus != null) {
                        // 调用 method2 方法获取状态值
                        Object statusObj = method2.invoke(devicestatus);
                        // 检查返回值是否为 null
                        if (statusObj != null) {
                            String status = (String) statusObj;
                            // 去除字符串首尾的双引号
                            deviceInfo.set状态(status.replaceAll("^\"|\"$", ""));
                        } else {
                            // 若返回值为 null，可设置默认值
                            deviceInfo.set状态("");
                        }
                    }
                    countStatusDP((String) method1.invoke(lastData), deviceInfo);
                    boardDeviceInfos.add(deviceInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return Result.success(boardDeviceInfos);
        }
    }
}
